import Vue from "vue";
import Vuex from "vuex";
import permission from "./modules/permission";
import user from "./modules/user";
import tagsView from "./modules/tagsView";
import persistence from "./modules/persistence";
import createPersistedState from "vuex-persistedstate";
import system from "./modules/system";

import chatList from "./modules/chatList";
import contactList from "./modules/contactList";
import groupList from "./modules/groupList";
import chat from "./modules/chat";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    // 主题设置
    theme: "default",

    // 语言设置
    language: "zh-CN",
    
    // 应用初始化状态
    isInitializing: false,
  },
  mutations: {
    // 主题设置
    SET_THEME(state, theme) {
      state.theme = theme;
    },

    // 语言设置
    SET_LANGUAGE(state, language) {
      state.language = language;
    },
    
    // 应用初始化状态
    SET_INITIALIZING(state, isInitializing) {
      state.isInitializing = isInitializing;
    },
  },
  actions: {
    // 设置主题
    setTheme({ commit }, theme) {
      commit("SET_THEME", theme);
      // 保存到localStorage
      localStorage.setItem("app_theme", theme);
    },

    // 设置语言
    setLanguage({ commit }, language) {
      commit("SET_LANGUAGE", language);
      // 保存到localStorage
      localStorage.setItem("app_language", language);
    },
  },
  modules: {
    permission,
    user,
    tagsView,
    system,
    persistence,

    chatList,
    contactList,
    groupList,
    chat,
  },
  // 定义全局getters 方便访问user 模块的roles
  getters: {
    // 应用初始化状态
    isInitializing: state => state.isInitializing,
    token: (state) => state.user.token,
    userLogin: (state) => state.user.userLogin,
    roles: (state) => state.user.roles,
    permission_routes: (state) => state.permission.routes,
    toolbarSelect: (state) => state.persistence.toolbarSelect,
    systemAnnouncements: (state) => state.system.systemAnnouncements,
    isLockScreen: (state) => state.system.isLockScreen,
    websiteConfig: (state) => state.system.websiteConfig,
    promptSounds: (state) => state.system.promptSounds,

    // 主题
    theme: (state) => state.theme,

    // 语言
    language: (state) => state.language,


    // 聊天列表
    chatList: (state) => state.chatList.list,

    // 联系人列表
    contactList: (state) => state.contactList.friends,

    // 群组列表
    groupList: (state) => state.groupList.list,

    // 聊天相关
    currentChat: (state) => state.chat.currentChat,
    currentChatId: (state) => state.chat.currentChatId,
    currentMessages: (state) => {
      if (!state.chat.messages || typeof state.chat.messages !== 'object') {
        return [];
      }
      return state.chat.messages[state.chat.currentChatId] || [];
    },
    isOnline: (state) => state.chat.isOnline,
    isSending: (state) => state.chat.isSending,
    totalUnreadCount: (state) => state.chat.totalUnreadCount,
  },
  plugins: [
    createPersistedState({
      storage: window.sessionStorage,
    }),
  ],
});
